package com.zhang.apidriver.service.impl;

import com.zhang.apidriver.remote.ServiceDriverClient;
import com.zhang.apidriver.remote.ServiceVerificationCodeClient;
import com.zhang.apidriver.service.VerificationCodeService;
import com.zhang.internalcommon.constant.CommonStatusEnum;
import com.zhang.internalcommon.constant.DriverCarConstant;
import com.zhang.internalcommon.constant.IdentityConstant;
import com.zhang.internalcommon.constant.TokenConstants;
import com.zhang.internalcommon.dto.ResponseResult;
import com.zhang.internalcommon.dto.VerificationCodeDTO;
import com.zhang.internalcommon.response.DriverUserExistsResponse;
import com.zhang.internalcommon.response.NumberCodeResponse;
import com.zhang.internalcommon.response.TokenResponse;
import com.zhang.internalcommon.utils.JwtUtils;
import com.zhang.internalcommon.utils.RedisPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 类功能描述
 *
 * @author Kye
 * @date 2025-04-13
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {
	@Autowired
	private ServiceDriverClient serviceDriverClient;

	@Autowired
	private ServiceVerificationCodeClient serviceVerificationCodeClient;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Override
	public ResponseResult checkAndsendVerificationCode(String driverPhone) {
		// 查询service-driver-user,该手机号的司机是否存在
 		ResponseResult<DriverUserExistsResponse> driverUserExistsResponseResponseResult = serviceDriverClient.getUser(driverPhone);
		DriverUserExistsResponse data = driverUserExistsResponseResponseResult.getData();
		int ifExists = data.getIfExists();
		if (ifExists == DriverCarConstant.DRIVER_NOT_EXISTS){
			return ResponseResult.fail(CommonStatusEnum.DRIVER_NOT_EXISTS.getCode(),CommonStatusEnum.DRIVER_NOT_EXISTS.getValue());
		}
		log.info(driverPhone+"的司机存在");

		// 获取验证码
		ResponseResult<NumberCodeResponse> numberResult = serviceVerificationCodeClient.numberCode(6);
		NumberCodeResponse numberCodeResponse = numberResult.getData();
		int numberCode = numberCodeResponse.getNumberCode();
		log.info("验证码："+numberCode);
		// 调用第三方获取验证码

		// 存入Redis
		String key = RedisPrefixUtils.generateKeyByPhone(driverPhone, IdentityConstant.DRIVER_IDENTITY);
		stringRedisTemplate.opsForValue().set(key,numberCode+"",2, TimeUnit.MINUTES);
		return ResponseResult.success();
	}

	/**
	 * 验证码登录注册
	 * @param driverPhone 电话
	 * @param verificationCode 验证码
	 * @return
	 */
	@Override
	public ResponseResult checkVerificationCode(String driverPhone, String verificationCode) {
		// 	根据手机号从redis查找验证码
		// 	生成key
		String key = RedisPrefixUtils.generateKeyByPhone(driverPhone,IdentityConstant.DRIVER_IDENTITY);
		// 	根据key获取value
		String codeRedis = stringRedisTemplate.opsForValue().get(key);
		// 	校验验证码
		if (StringUtils.isBlank(codeRedis)) {
			return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
		}
		if (!verificationCode.trim().equals(codeRedis.trim())) {
			return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR.getCode(), CommonStatusEnum.VERIFICATION_CODE_ERROR.getValue());
		}

		// 	判断原来是否有用户，并进行处理
		// VerificationCodeDTO verificationCodeDTO = new VerificationCodeDTO();
		// verificationCodeDTO.setPassengerPhone(driverPhone);
		// passengerUserClient.loginOrRegister(verificationCodeDTO);

		// 	颁发令牌
		String accessToken = JwtUtils.generateToken(driverPhone, IdentityConstant.DRIVER_IDENTITY, TokenConstants.ACCESS_TOKEN_TYPE);
		String refreshToken = JwtUtils.generateToken(driverPhone, IdentityConstant.DRIVER_IDENTITY,TokenConstants.REFRESH_TOKEN_TYPE);
		// 将token存到redis
		String accessTokenKey = RedisPrefixUtils.generateTokenKey(driverPhone, IdentityConstant.DRIVER_IDENTITY,TokenConstants.ACCESS_TOKEN_TYPE);
		stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 15, TimeUnit.DAYS);
		String refreshTokenKey = RedisPrefixUtils.generateTokenKey(driverPhone, IdentityConstant.DRIVER_IDENTITY,TokenConstants.REFRESH_TOKEN_TYPE);
		stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 16, TimeUnit.DAYS);

		// 响应
		TokenResponse tokenResponse = new TokenResponse();
		tokenResponse.setAccessToken(accessToken);
		tokenResponse.setRefreshToken(refreshToken);

		return ResponseResult.success(tokenResponse);
	}
}
